/**
 * get, post, delete 方法的封装
 *
 * 本项目 API 文档：
 * -- https://app.swaggerhub.com/apis/imageslr/weapp/1.0.1
 */

import { getToken } from './permission'
var Promise = require('./es6-promise')
import Promisify from './promisify'

/**
 * 服务器根路径
 */
// export const BASE_URL = 'http://laptop-ok5jgg2e.local:8200/api'
export const BASE_URL = 'http://192.168.0.108:8200/api'
export const DOMAIN_NAME = 'http://192.168.0.108:8200'

/**
 * get 方法
 * @param relativeUrl 相对路径 必填
 * @param param 参数 可选 12
 * @param header 请求头参数 可选
 * @returns {Promise}
 */
export function get(relativeUrl, param, query, header) {
  return requestWithModal('GET', relativeUrl, param, query, header)
}

/**
 * post 方法
 */
export function post(relativeUrl, param, query, header) {
  return requestWithModal('POST', relativeUrl, param, query, header)
}

/**
 * post 方法
 */
export function put(relativeUrl, param, query, header) {
  return requestWithModal('PUT', relativeUrl, param, query, header)
}

/**
 * del 方法
 */
export function del(relativeUrl, param, query, header) {
  return requestWithModal('DELETE', relativeUrl, param, query, header)
}

/**
 * 请求失败时，显示服务器的错误信息(data.message)或微信的错误信息(errMsg)
 */
export function requestWithModal(method, relativeUrl, param, query, header) {
  return request(method, relativeUrl, param, query, header).catch((res) => {
    console.warn('请求失败：', res)
    if (res.statusCode === 400) { // 400 验证错误
      const err_msg = res.data.errors
      wx.showToast({
        title: JSON.stringify(err_msg),
        icon: 'none'
      })
    } else if (res.statusCode === 401) {
      // 未授权，跳转到登录
      wx.redirectTo({
        url: '../login/login'
      })
    }
    else {
      wx.showModal({
        content: '发生未知错误，请修复',
        showCancel: false
      })
    }
    return Promise.reject(res)
  })
}
export function uploadImage(url, imgList, payload) {
  // 如果是本地照片，直接上传，这里好像都是本地图片
  var upload = function (imgPath) {
    return new Promise((resolve, reject) => {
      if (imgPath.indexOf(DOMAIN_NAME) === -1) {
        wx.showLoading({ title: '文件上传中', mask: true })
        uploadFile(BASE_URL + url, imgPath, payload).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      } else {
        resolve(imgPath)
      }
    })
  }
  var uploads = new Array(imgList.length)
  for (var i in imgList) {
    uploads[i] = upload(imgList[i])
  }
  return Promise.all(uploads).then(res => {
    return res
  })
}

/**
 * request 基类方法
 * 状态码 ≥ 400 时，返回 rejected 状态的 promise
 * @param method 请求方式 必填
 * @param relativeUrl 相对路径 必填
 * @param param 参数 可选
 * @param header 请求头参数 可选
 * @returns {Promise} 返回响应完整内容
 */
export function request(method, relativeUrl, param, query, header) {
  // 删除所有为 null 的参数
  for (var key in param) {
    if (param[key] === null) {
      delete param[key]
    }
  }
  if (query) {
    relativeUrl = query_params(relativeUrl, query)
  }

  let response, error, statusCode
  return new Promise((resolve, reject) => {
    wx.request({
      url: BASE_URL + relativeUrl,
      method: method,
      header: Object.assign({
        'Content-Type': 'application/json',
        'Authorization': getToken()
      }, header),
      data: param || {},
      success(res) {
        console.warn('请求成功2：', res)
        response = res.data
        statusCode = res.statusCode
        if (res.statusCode < 400) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      fail(err) {

        error = err
        reject(err)
      },
      complete() {
        console.info('==============>请求开始<==============')
        console.warn(method, BASE_URL + relativeUrl)
        if (param) console.warn('参数：', param)
        if (response) {
          console.warn('请求成功：', response)
        } else if (statusCode === 204) {
          console.warn('删除成功：')
        }
        else {
          console.warn('请求失败：', error)
        }
        console.info('==============>请求结束<==============')
      }
    })
  })
}

function query_params(url, obj) {
  let result = '';
  let item;
  if (!url.includes("?")) {
    result += "?"
  }
  for (item in obj) {
    if (obj[item] && String(obj[item])) {
      result += `${item}=${obj[item]}&`;
    }
  }
  return url + result;
}


function uploadFile(url, filePath, payload) {
  return Promisify(wx.uploadFile)({
    filePath: filePath,
    name: 'image',
    formData: payload,
    url: url,
    header: {
      'Authorization': getToken()
    }
  }).then(res => {
    if (res.statusCode == 400) {
      try {
        res.data = JSON.parse(res.data)
        const err_msg = res.data.errors
        wx.showToast({
          title: JSON.stringify(err_msg),
          icon: 'none'
        })
      } catch (e) { }
      // wx.showModal({
      //   title: '上传图片失败',
      //   content: '未知错误',
      //   showCancel: false
      // })
      return Promise.reject(new Error('上传图片失败'))
    } else {
      return res
    }
  })
}